package com.ebor.utils.common;

import com.ebor.utils.exception.SysRuntimeException;
import com.alibaba.fastjson.annotation.JSONField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 返回参数统一
 *
 * @param <T>
 * @author C
 */
@ApiModel(value = "全局响应参数", description = "全局响应参数")
@Getter
@Setter
@ToString
public class Response<T> {

    @ApiModelProperty(value = "状态码", name = "respCode", example = "0")
    private String respCode;
    @ApiModelProperty(value = "提示信息", name = "respMsg", example = "请求成功")
    private String respMsg;
    @ApiModelProperty(value = "时间戳", name = "time", example = "2021-10-10 11:12:10")
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date time;
    @ApiModelProperty(value = "数据项", name = "data")
    private T data;

    public Response(T data) {
        this.respCode = HttpStatus.SUCCESS.getRespCode();
        this.respMsg = HttpStatus.SUCCESS.getRespMsg();
        this.data = data;
        this.time = new Date();
    }

    public Response(T data, String respMsg) {
        this.respCode = HttpStatus.SUCCESS.getRespCode();
        this.respMsg = respMsg;
        this.data = data;
        this.time = new Date();
    }

    public Response(T data, String respCode, String respMsg) {
        this.respCode = respCode;
        this.respMsg = respMsg;
        this.data = data;
        this.time = new Date();
    }

    public static Response<Map<String, Object>> success() {
        Map<String, Object> res = new HashMap<>(0);
        return new Response<>(res);
    }

    public static <T> Response<T> success(T data) {
        return new Response<>(data);
    }

    public static <T> Response<T> success(T data, String respMsg) {
        return new Response<>(data, respMsg);
    }

    public static <T> Response<T> error(String respCode, String respMsg) {
        return new Response<>(null, respCode, respMsg);
    }

    public static <T> Response<T> error(SysRuntimeException e) {
        return new Response<>(null, e.getCode(), e.getMessage());
    }

    public static <T> Response<T> error(HttpStatus httpStatus) {
        return new Response<>(null, httpStatus.getRespCode(), httpStatus.getRespMsg());
    }
}
